package com.novel.common.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 本地ip库获取ip工具
 *
 * @author novel
 * @date 2019/12/19
 */
public class IPDataHandler {

    private static final Pattern IPV4_PATTERN = Pattern.compile("^(([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){1}(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){2}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$");
    private static byte[] data;

    private static long indexSize;
    private static Map<String, String[]> cacheMap = null;
    private static final String PATH = "datx/17monipdb.datx";

    static {
        try {
            InputStream inputStream = new ClassPathResource(PATH).getInputStream();
            data = FileCopyUtils.copyToByteArray(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            try {
                String filePath = ResourceUtils.getURL("classpath:").getPath() + PATH;
                filePath = filePath.substring(1);
                Path path = Paths.get(filePath);
                data = Files.readAllBytes(path);
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        indexSize = bytesToLong(data[0], data[1], data[2], data[3]);
        cacheMap = new HashMap<>();
    }

    public static boolean isIPv4Address(String input) {
        return IPV4_PATTERN.matcher(input).matches();
    }

    public static long bytesToLong(byte a, byte b, byte c, byte d) {
        return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
    }

    private static int str2Ip(String ip) {
        String[] ss = ip.split("\\.");
        int a, b, c, d;
        a = Integer.parseInt(ss[0]);
        b = Integer.parseInt(ss[1]);
        c = Integer.parseInt(ss[2]);
        d = Integer.parseInt(ss[3]);
        return (a << 24) | (b << 16) | (c << 8) | d;
    }

    public static int str2Ip2(String ip) {
        try {
            byte[] bytes = java.net.InetAddress.getByName(ip).getAddress();

            return ((bytes[0] & 0xFF) << 24) |
                    ((bytes[1] & 0xFF) << 16) |
                    ((bytes[2] & 0xFF) << 8) |
                    bytes[3];
        } catch (java.net.UnknownHostException e) {
            e.printStackTrace();
        }

        return 0;
    }


    public static long ip2long(String ip) {
        return int2long(str2Ip(ip));
    }

    private static long int2long(int i) {
        long l = i & 0x7fffffffL;
        if (i < 0) {
            l |= 0x080000000L;
        }
        return l;
    }


    public static String[] find(String ip) {
        if (!isIPv4Address(ip)) {
            throw new RuntimeException("Not the correct IP address");
        }

        if (cacheMap.containsKey(ip)) {
            return cacheMap.get(ip);
        }

        long val = ip2long(ip);
        int start = 262148;
        int low = 0;
        int mid = 0;
        int high = new Long((indexSize - 262144 - 262148) / 9).intValue() - 1;
        int pos = 0;
        while (low <= high) {
            mid = new Double((low + high) >> 1).intValue();
            pos = mid * 9;

            long s = 0;
            if (mid > 0) {
                int pos1 = (mid - 1) * 9;
                s = bytesToLong(data[start + pos1], data[start + pos1 + 1], data[start + pos1 + 2], data[start + pos1 + 3]);
            }

            long end = bytesToLong(data[start + pos], data[start + pos + 1], data[start + pos + 2], data[start + pos + 3]);
            if (val > end) {
                low = mid + 1;
            } else if (val < s) {
                high = mid - 1;
            } else {

                byte b = 0;
                long off = bytesToLong(b, data[start + pos + 6], data[start + pos + 5], data[start + pos + 4]);
                long len = bytesToLong(b, b, data[start + pos + 7], data[start + pos + 8]);

                int offset = new Long(off - 262144 + indexSize).intValue();

                byte[] loc = Arrays.copyOfRange(data, offset, offset + new Long(len).intValue());
                String[] address = new String(loc, StandardCharsets.UTF_8).split("\t", 0);
                cacheMap.put(ip, address);
                return address;
            }
        }
        cacheMap.put(ip, null);
        return null;
    }
}